﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Authentication;
//using Castle.Components.Common.EmailSender;
using Castle.MonoRail.Framework;
using MyMessenger.Core.Services;
using MyMessenger.Core;
using System.Web.Security;
using MyMessenger.Web.Services;

namespace MyMessenger.Web.Controllers
{
    [Layout("default"), Rescue("generalerror")]
    public class LoginController : SmartDispatcherController
    {
        private ISecurityService securityService;
        private AuthenticationService authService;
        private IMessageService messageService;

        public LoginController(ISecurityService securityService, AuthenticationService authService, IMessageService messageService)
        {
            this.securityService = securityService;
            this.authService = authService;
            this.messageService = messageService;
        }

        public void Index()
        {
        }

        [AccessibleThrough(Verb.Post)]
        public void LogIn(string username, string password, bool rememberMe, string returnUrl)
        {
            try
            {
                User user = securityService.Authenticate(username, password, Request.UserHostAddress);
                PropertyBag["user"] = user;
                authService.SetAuthCookie(user, rememberMe, GetCookiePath());

                SendHelloMessageToEveryone(user);

                if (returnUrl != null)
                    Redirect(returnUrl);
                else
                    Redirect("messege", "index");

                return;
            }
            catch (AuthenticationException ex)
            {
                if (Logger.IsErrorEnabled)
                    Logger.Error("Could not log user in", ex);
                Flash["error"] = ex.Message;
            }
            catch (Exception ex)
            {
                if (Logger.IsFatalEnabled)
                    Logger.Fatal("Error performing log in", ex);
                Flash["error"] = "Could not log in due to a system error. Please contact the site administrator!";
            }

            Flash["username"] = username;
            RedirectToAction("index", "url=" + returnUrl);
        }

        private void SendHelloMessageToEveryone(User user)
        {
            messageService.AddMessage(user, null, "entered");
        }

        private string GetCookiePath()
        {
            if (Context == null)
                return "ntni_chat_abasz";
            else
                return Context.ApplicationPath + "/";
        }

        public void LogOut()
        {
            authService.SignOut();
            Redirect("login", "index");
        }
    }
}
